#!/bin/bash

# 脚本描述：一键上传指定目录代码到 GitLab，支持 HTTP/HTTPS 选择

# --- 配置 ---
GITLAB_URL="gitlab.uoto.fun"

# --- 函数 ---

# 检查 Git 是否安装
check_git() {
  if ! command -v git &> /dev/null; then
    echo "错误：Git 未安装。请先安装 Git。"
    exit 1
  fi
}

# 选择协议
select_protocol() {
  select PROTOCAL in "HTTP" "HTTPS"; do
    case $PROTOCAL in
      "HTTP")
        PROTOCOL="http"
        break
        ;;
      "HTTPS")
        PROTOCOL="https"
        break
        ;;
      *)
        echo "无效的选择。请重新选择。"
        ;;
    esac
  done
}

# 获取用户输入
get_input() {
  read -p "请输入项目目录绝对路径: " PROJECT_PATH
  read -p "请输入 GitLab 群组名称: " GITLAB_GROUP
  read -p "请输入仓库名称: " REPOSITORY_NAME
  read -p "请输入目标分支 (默认main): " TARGET_BRANCH
  if [ -z "$TARGET_BRANCH" ]; then
    TARGET_BRANCH="main"
  fi
  read -p "请输入 GitLab 访问令牌: " GITLAB_TOKEN  # 使用 -s 隐藏输入
  echo  # 换行
}

# 上传代码
upload_code() {
  # 检查目录是否存在
  if [ ! -d "$PROJECT_PATH" ]; then
    echo "错误：目录 '$PROJECT_PATH' 不存在。"
    exit 1
  fi

  # 切换到要上传的目录
  cd "$PROJECT_PATH" || { echo "无法切换到目录 '$PROJECT_PATH'"; exit 1; }

  # 初始化 Git 仓库 (如果还没有)
  if [ ! -d ".git" ]; then
    git init
    git add .
    git commit -m "Initial commit"
  fi

  # 添加远程仓库
  git remote add origin "${PROTOCOL}://${GITLAB_TOKEN}@${GITLAB_URL}/${GITLAB_GROUP}/${REPOSITORY_NAME}.git"

  # 推送代码
  git push -u origin "$TARGET_BRANCH"

  echo "代码上传成功！"
}

# --- 主程序 ---

check_git

select_protocol

get_input

upload_code
